--
-- Author: yawei.zhu
-- Date: 2018-09-11 11:06:56
--
-- DynastyBattleController
--
local PvpChallengeFailView = require("app.pvp.views.PvpChallengeFailView")
local PvpDynastyView = require("app.pvp.views.PvpDynastyView")

local DynastyBattleView = import("..views.DynastyBattleView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    self._model = app:getInst("DynastyBattleModel")
end

function ClassRef:removeListeners()
    self.super.removeListeners(self)
end

function ClassRef:listEvent()
    return {
        "onTeamUpdate",
        "onTeamMemberUpdate",
        "onTeamLeaderChanged",
        -- "onTeamSettingUpdate",
    }
end

function ClassRef:onEvent(eventName, data)
    if eventName == "onTeamUpdate" then -- 队伍更新
        self:updateTeamInfo()
    elseif eventName == "onTeamMemberUpdate" or eventName == "onTeamLeaderChanged" then
        self:updateTeamInfo()
    elseif eventName == "onTeamSettingUpdate" then -- 队伍设置更新
        -- donothing
    elseif eventName == "onTeamNewApplyer" then -- 来新申请人
        -- donothing
    end
end

function ClassRef:openView(data)

    local function confirmOpen(townInfo)
        if cc.isDead(self._view) then
            self._view = DynastyBattleView.new(app.mvc.VIEWTYPE_BLUR)
            self._view:onCloseView(handler(self, self.closeView))
            self._view:onClearView(handler(self, self.clearView))
            self._view:onOperate(handler(self, self.onOperate))
            self:addChild(self._view, data)
        end
    
        self._view:show()
    
        local TeamModel = app:getInst("TeamModel")
        self._view:updateView(townInfo, data[2], TeamModel:getMembers() )
    end

    -- 先拉取城镇信息，判断是否在开战阶段
    self._model:reqGetTownInfo(data[1], function(townInfo)
        dump(townInfo.phase)
        if townInfo and (townInfo.phase == "READY" or townInfo.phase == "FIGHT") then
            confirmOpen(townInfo)
        else
            display.pushToast( L("dynastybattle_notice1") )
        end
    end)

end
function ClassRef:closeView(data)
    if self._view then
        self:removeChild(self._view, data)
        self:clearView()
    end
end
function ClassRef:clearView()
    if self._view then
        self._view = nil
    end
end

-------------------------------------------------------
function ClassRef:updateTownInfo(townInfo)
    if not self:isViewAlive() then return end
    self._view:updateTownInfo(townInfo)
end

function ClassRef:updateTeamInfo()
    if not self:isViewAlive() then return end
    local TeamModel = app:getInst("TeamModel")
    self._view:updateTeamMember( TeamModel:getMembers() )
end

-- 公会战结算 （只显示当前所在战场的结算，如果不在战场也不显示结算）
function ClassRef:showDynastyAccount(msg)
    dump(msg)
    -- 判断当前是否在公会战场
    if not app:sendMsg("DynastyMapModel", "isDynastyMap") then
        return 
    end

    -- 通过当前据点Id找到所属领地ID，然后查到领地信息
    local mapName = ""
    local mapId = MapManager:getMapId()
    local holdInfo = GD:getStrongholdInfoByMapId(mapId) -- 据点信息
    if not holdInfo then 
        print("Error: holdInfo = nil, mapId = ", mapId)
        return
    end

    if tonumber(holdInfo.districtID) ~= msg.townId then return end -- 不是当前领地的结算

    -- 领地信息
    local districtInfo = GD:getDistrictInfoById(holdInfo.districtID)
    mapName = L(districtInfo.name)

    -- mapName = "【" .. mapName .. "】"

    local view
    local myGuildId = tostring(UD:getGuildId())
    if msg.newOwnerGuildId == myGuildId then -- 成功
        view = PvpDynastyView.new()
        local str = ""
        if msg.oldOwnerGuildId == myGuildId then
            str = string.format(L("KeepCity"), mapName)
        else
            str = string.format(L("CaptureCity"), mapName)
        end

        -- 奖励
        local itemDatas = {}
        itemDatas[1] = UD:parseRewardToBagItem("112|0|" .. msg.contributeVal) -- 公会经验
        itemDatas[2] = UD:parseRewardToBagItem("1|71115003|" .. msg.roseGoldNum) -- 玫瑰金币
        view:refresh(str, itemDatas)
    else
        view = PvpChallengeFailView.new()
        local str = ""
        if msg.oldOwnerGuildId == myGuildId then
            str = string.format(L("LoseCity"), mapName)
        else
            str = string.format(L("CanNotCaptureCity"), mapName)
        end

        -- 奖励
        local itemDatas = {}
        itemDatas[1] = UD:parseRewardToBagItem("112|0|" .. msg.contributeVal) -- 公会经验
        itemDatas[2] = UD:parseRewardToBagItem("1|71115003|" .. msg.roseGoldNum) -- 玫瑰金币
        view:refreshByDynastyFailed(str, itemDatas)
    end

    view:onCloseView(function() 
            view:removeFromParent()
            app.session:request("pb_map.C2S_BackToLastMap",{}) -- 回到主城
        end)
    view:show()
    UIHandler:addPopupUi(view)
end

-- 展示战备UI
function ClassRef:showTeamReady()
    local params = {
        idx = 1,
        targetId = Enums.TeamTarget.dynastyBattle
    }

    local teamNum = app:getInst("TeamModel"):getMemberNum()
    if teamNum < 5 then
        local function teamMemberEnsureDlg()
            local creataeTeamDialog = display.newConfirmDialog( L("dynastybattle_notice3"), function() -- 确定
                -- self:onOperate("TeamMatching_changeAutoRecruitTarget")-- 切换自动招募目标
                app:sendMsg("NewTeamReadyAndSettingController", "openView", params)
            end)
            UIHandler:addPopDialog( creataeTeamDialog )
        end
        teamMemberEnsureDlg()
    else
        -- self:onOperate("TeamMatching_changeAutoRecruitTarget")-- 切换自动招募目标
        app:sendMsg("NewTeamReadyAndSettingController", "openView", params)
    end

end

-------------------------------------------------------
function ClassRef:onOperate(op, data)
    print("DynastyBattleController:onOperate op = " .. op)
    if op == "reqTownInfo" then
        self._model:reqGetTownInfo(data)
    elseif op == "openTeamview" then
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_CREATE_TEAM, mode = "open"})
    elseif op == "reqEnterDynastyBattle" then
        self._model:setDynastyBattleID(data[1], data[2]) -- 暂存townId 和 据点Id
        -- 展示战备UI
        self:showTeamReady()
    elseif op == "openGuildMember" then
        UIHandler:handleMessage({id = Constant.FUNC_TYPE_GANG, mode = "open"})
    elseif op == "openInviteView" then
        app:sendMsg("NewTeamApplyController", "openView", { 1, 2 } ) -- 弹出标签1-邀请标签
    end
end

return ClassRef
